package com.example.base.mvvm

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.Observable
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType
import java.text.SimpleDateFormat

abstract class BaseActivity<VDB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
    //拿到集成baseActivity之后的实际Activity（子类）中的2个泛型
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }
    protected val binding: VDB by lazy {
        //拿到第一个泛型的class
        val clazz = type[0] as Class<VDB>
        //通过反射，拿到activity中的inflate的方法
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        //通过反射放大的调用，自定绑定第一个参数的值（布局）
        method.invoke(null, layoutInflater) as VDB
    }

    //直接通过泛型拿到对应的viewmodel的class，来进行实例化
    protected val vm: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.e("TagA", "error:${t.message}")
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        vm.onFailed.observe(this, ::onError)
        //与上面方法是等价的
//        vm.onFailed.observe(this,object :Observer<Throwable>{
//            override fun onChanged(t: Throwable?) {
//                onError(t!!)
//            }
//
//        })

        initView()
        initData()
    }

    abstract fun initData()

    abstract fun initView()

    fun getTime(): String {
        val time = System.currentTimeMillis()
        var tampTime = TimeUtils.millis2String(time, SimpleDateFormat("yyyy-MM-dd"))
        tampTime += "T"
        tampTime += TimeUtils.millis2String(time, SimpleDateFormat("HH:mm:ss"))
        tampTime += "Z"
        return tampTime
    }
}